package gr.handmademarket.ui.panels;

import gr.handmademarket.bl.operations.NewsLetterOperation;
import gr.handmademarket.po.implementations.NewsLetterReceipient;
import gr.handmademarket.util.SendEmailUtils;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.EmailTextField;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;

/**
 * the login panel.
 */
public class NewsLetterPanel 
extends Panel{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * the form containing the user email.
	 */
	@SuppressWarnings("nls")
	private Form<NewsLetterReceipient> form = new Form<NewsLetterReceipient>("form", new CompoundPropertyModel<NewsLetterReceipient>(new NewsLetterReceipient()));
	
	/**
	 * the email field.
	 */
	@SuppressWarnings("nls")
	private EmailTextField emailField = new EmailTextField("email");
	
		
	/**
	 * submit link.
	 */
	@SuppressWarnings("nls")
	private AjaxButton submit = new AjaxButton("registerBtn", form) {

		/**
		 * serialVersionUID.
		 */
		private static final long serialVersionUID = 1L;

		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			NewsLetterOperation operation = new NewsLetterOperation();
			operation.setReceipient(form.getModelObject());
			try {
				operation.execute();
				//SendEmailUtils emailUtility = new SendEmailUtils("george.pagonis@gmail.com", form.getModelObject().getEmail(), "babushka", "get ready for babushka");
				//emailUtility.send();
				form.setModelObject(new NewsLetterReceipient());
				target.add(NewsLetterPanel.this.getParent());
			} catch (RuntimeException e){
				error(e.getMessage());
				Component feedbackPanel = NewsLetterPanel.this.getParent().get("feedbackPanel");
				System.out.println("feedbackpanel found: " + Boolean.toString(feedbackPanel != null) );
				target.add(feedbackPanel);
			}
		}
		
		@Override
		public void onError(AjaxRequestTarget target, Form<?> form1) {
			Component feedbackPanel = NewsLetterPanel.this.getParent().get("feedbackPanel");
			System.out.println("feedbackpanel found: " + Boolean.toString(feedbackPanel != null) );
			target.add(feedbackPanel);
		}
		
	};

	/**
	 * Creates a new LoginPanel object. 
	 *
	 * @param id
	 */
	public NewsLetterPanel(String id) {
		super(id);
		emailField.setRequired(true);
		add(form);
		form.add(emailField,submit);
	}


}
